<template>
  <div class="admin-management">
    <h1>管理员管理</h1>
    
    <a-card class="admin-card">
      <a-button type="primary" @click="showAddAdminModal" style="margin-bottom: 16px;">
        添加管理员
      </a-button>
      
      <a-table
        :columns="columns"
        :data-source="admins"
        :loading="loading"
        :pagination="{ pageSize: 10 }"
        rowKey="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="primary" size="small" @click="editAdmin(record)">编辑</a-button>
              <a-popconfirm
                title="确定要删除此管理员吗?"
                ok-text="确定"
                cancel-text="取消"
                @confirm="deleteAdmin(record.id)"
              >
                <a-button type="danger" size="small">删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
    
    <!-- 添加/编辑管理员的模态框 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="isEditing ? '编辑管理员' : '添加管理员'"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form :model="formState" :rules="rules" ref="formRef">
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="formState.username" />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="formState.email" />
        </a-form-item>
        <a-form-item label="密码" name="password" v-if="!isEditing">
          <a-input-password v-model:value="formState.password" />
        </a-form-item>
        <a-form-item label="确认密码" name="confirmPassword" v-if="!isEditing">
          <a-input-password v-model:value="formState.confirmPassword" />
        </a-form-item>
        <a-form-item label="角色" name="role">
          <a-select v-model:value="formState.role">
            <a-select-option value="admin">管理员</a-select-option>
            <a-select-option value="super_admin">超级管理员</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
export default {
  name: 'AdminManagement',
  data() {
    return {
      admins: [],
      loading: false,
      modalVisible: false,
      isEditing: false,
      currentAdminId: null,
      formState: {
        username: '',
        email: '',
        password: '',
        confirmPassword: '',
        role: 'admin'
      },
      rules: {
        username: [{ required: true, message: '请输入用户名' }],
        email: [
          { required: true, message: '请输入邮箱' },
          { type: 'email', message: '请输入有效的邮箱地址' }
        ],
        password: [{ required: true, message: '请输入密码' }],
        confirmPassword: [
          { required: true, message: '请确认密码' },
          ({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || getFieldValue('password') === value) {
                return Promise.resolve();
              }
              return Promise.reject(new Error('两次输入的密码不一致'));
            },
          }),
        ],
        role: [{ required: true, message: '请选择角色' }]
      },
      columns: [
        {
          title: 'ID',
          dataIndex: 'id',
          key: 'id',
        },
        {
          title: '用户名',
          dataIndex: 'username',
          key: 'username',
        },
        {
          title: '邮箱',
          dataIndex: 'email',
          key: 'email',
        },
        {
          title: '角色',
          dataIndex: 'role',
          key: 'role',
          customRender: ({ text }) => {
            return text === 'super_admin' ? '超级管理员' : '管理员';
          }
        },
        {
          title: '创建时间',
          dataIndex: 'created_at',
          key: 'created_at',
        },
        {
          title: '操作',
          key: 'action',
        },
      ],
    };
  },
  mounted() {
    this.fetchAdmins();
  },
  methods: {
    async fetchAdmins() {
      this.loading = true;
      try {
        // 这里应该调用获取管理员列表的API
        // const response = await this.$http.get('/api/admins/');
        // this.admins = response.data;
        
        // 模拟数据
        this.admins = [
          {
            id: 1,
            username: 'admin',
            email: 'admin@example.com',
            role: 'super_admin',
            created_at: '2023-01-01 12:00:00'
          },
          {
            id: 2,
            username: 'manager',
            email: 'manager@example.com',
            role: 'admin',
            created_at: '2023-01-02 12:00:00'
          }
        ];
      } catch (error) {
        console.error('获取管理员列表失败:', error);
        this.$message.error('获取管理员列表失败');
      } finally {
        this.loading = false;
      }
    },
    showAddAdminModal() {
      this.isEditing = false;
      this.formState = {
        username: '',
        email: '',
        password: '',
        confirmPassword: '',
        role: 'admin'
      };
      this.modalVisible = true;
    },
    editAdmin(record) {
      this.isEditing = true;
      this.currentAdminId = record.id;
      this.formState = {
        username: record.username,
        email: record.email,
        role: record.role
      };
      this.modalVisible = true;
    },
    async handleModalOk() {
      try {
        await this.$refs.formRef.validate();
        
        if (this.isEditing) {
          // 调用编辑管理员API
          // await this.$http.put(`/api/admins/${this.currentAdminId}/`, {
          //   username: this.formState.username,
          //   email: this.formState.email,
          //   role: this.formState.role
          // });
          this.$message.success('管理员信息更新成功');
        } else {
          // 调用添加管理员API
          // await this.$http.post('/api/admins/', {
          //   username: this.formState.username,
          //   email: this.formState.email,
          //   password: this.formState.password,
          //   role: this.formState.role
          // });
          this.$message.success('管理员添加成功');
        }
        
        this.modalVisible = false;
        this.fetchAdmins();
      } catch (error) {
        console.error('表单验证失败:', error);
      }
    },
    handleModalCancel() {
      this.modalVisible = false;
    },
    async deleteAdmin(id) {
      try {
        // 调用删除管理员API
        // await this.$http.delete(`/api/admins/${id}/`);
        this.$message.success('管理员删除成功');
        this.fetchAdmins();
      } catch (error) {
        console.error('删除管理员失败:', error);
        this.$message.error('删除管理员失败');
      }
    }
  }
};
</script>

<style scoped>
.admin-management {
  padding: 24px;
}

.admin-card {
  margin-top: 16px;
}
</style>